import java.util.ArrayList;
import java.util.List;

public class Solution1028 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode recoverFromPreorder(String traversal) {
        int p=0;
        List<TreeNode> list=new ArrayList<>();
        while (p<traversal.length()){
            int[] ans=search(p,traversal);
            p=ans[2];
            if (ans[0]==list.size()){
                list.add(new TreeNode(ans[1]));
            }else{
                list.set(ans[0],new TreeNode(ans[1]));
            }
            if (ans[0]!=0){
                TreeNode father=list.get(ans[0]-1);
                if (father.left==null){
                    father.left=list.get(ans[0]);
                }else{
                    father.right=list.get(ans[0]);
                }
            }
        }
        return list.get(0);
    }

    private int[] search(int p, String traversal) {
        int c=0;
        while (p<traversal.length() && traversal.charAt(p)=='-'){
            c++;
            p++;
        }
        int m=0;
        while (p<traversal.length() && traversal.charAt(p)!='-'){
            m=m*10+traversal.charAt(p)-'0';
            p++;
        }
        return new int[]{c,m,p};
    }

    public static void main(String[] args) {
        System.out.println(new Solution1028().recoverFromPreorder("1-2--3---4-5--6---7").right.left.left.val);
    }
}
